import Flutter
import UIKit


public class SpeechPlayPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
      let channel = FlutterMethodChannel(name: "speech_play", binaryMessenger: registrar.messenger())
      let instance = SpeechPlayPlugin()
      registrar.addMethodCallDelegate(instance, channel: channel)
      
      SpeechPlayHelper.shared.setMethodChannel(channel: channel)
      SpeechPlayHelper.shared.setDartIsReady(true)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
  let arguments = call.arguments as? Dictionary<String, Any>
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
    case "getExternalFilesDir":
        if let path = StorageUtils.getSafeStoragePath(subdirectory: "Downloads") {
            result(path)
        }
    case "speechPlay":
        guard let arguments = arguments else {
            result(FlutterError(code: "invalid_argument", message: "No data was provided.", details: nil))
            return
        }
        let path = arguments["path"] as! String
        let startTime = arguments["startTime"] as! TimeInterval
        let duration = arguments["duration"] as! TimeInterval
        SpeechPlayer.startSpeech(filePath: path, startTime: startTime, duration: duration, result: result)
    case "pausePlay":
        SpeechPlayer.pauseSpeech(result: result)
    case "cancelPause":
        SpeechPlayer.cancelPause()
    case "playSeekTo":
        guard let arguments = arguments else {
            result(FlutterError(code: "invalid_argument", message: "No data was provided.", details: nil))
            return
        }
        let startTime = arguments["startTime"] as! TimeInterval
        SpeechPlayer.playSeekTo(startTime: startTime)
    case "switchSpeaker":
        guard let arguments = arguments else {
            result(FlutterError(code: "invalid_argument", message: "No data was provided.", details: nil))
            return
        }
        let enable = arguments["enable"] as! Bool
        SensorUtil.shared.switchSpeaker(enable: enable)
        result(true)
   
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
